import { ElMessage } from "element-plus";
export const copyText = (text) => {
  let span = document.createElement("span");
  span.innerHTML = text;
  text = span.textContent;
  span.remove();
  let input = document.createElement("input");
  input.setAttribute("readonly", "readonly");
  input.setAttribute("value", text);
  document.body.appendChild(input);
  input.select();
  if (document.execCommand("copy")) {
    document.execCommand("copy");
    ElMessage?.success("复制成功");
  }
  document.body.removeChild(input);
};


/**
 * 判断是否是二维数组
 * @param {*} arr 
 * @returns 
 */
export function flattenAndRemoveDuplicates(arr) {
  function isArray(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  }
  function flattenAndRemoveDuplicatesFromArray(arr) {
    const uniqueArray = [...new Set(arr)];
    return uniqueArray;
  }
  function processArray(arr) {
    if (!isArray(arr)) {
      console.error("Input is not an array");
      return [];
    }
    if (arr.every(item => !isArray(item))) {
      return flattenAndRemoveDuplicatesFromArray(arr);
    }
    const flattenedArray = arr.flat();
    return flattenAndRemoveDuplicatesFromArray(flattenedArray);
  }
  return processArray(arr);
}


/**
 * 导出表格头和数据进行处理
 * @param {*} data 
 * @param {*} tHeader 
 * @param {*} filterVal 
 * @returns 
 */
export function mapTableData(data, tHeader, filterVal) {
  return data.map((row) => {
    const mappedRow = {};
    tHeader.forEach((header, index) => {
      mappedRow[header] = row[filterVal[index]];
    });
    return mappedRow;
  });
}

/**
 * 简单防抖函数
 * @param {Function} fn - 要执行的函数
 * @param {Number} delay - 延迟时间（毫秒）
 * @returns {Function}
 */
export function debounce(fn, delay = 300) {
  let timer = null;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

